<template>
  <div class="components-add-or-update">
    <el-dialog
      v-model="visible"
      :title="!dataForm.formId ? $t('brand.add') : $t('brand.revise')"
      :close-on-click-modal="false"
      style="min-width:700px;"
      @close="closeDialogHandle"
    >
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        label-width="110px"
        @submit.prevent
      >
        <el-form-item
          :label="$t('formData.formName')"
          prop="formName"
        >
          <el-input
            v-model="dataForm.formName"
            :placeholder="$t('formData.pleaseEnterTheReportName')"
            maxlength="50"
            show-word-limit
            clearable
          />
        </el-form-item>
        <el-form-item
          :label="$t('formData.timePeriod')"
          prop="timeType"
          class="time-type"
        >
          <el-radio-group v-model="dataForm.timeType">
            <el-radio :label="1">
              {{ $t('formData.natureDay') }}
            </el-radio>
            <el-radio :label="2">
              {{ $t('formData.natureWeek') }}
            </el-radio>
            <el-radio :label="3">
              {{ $t('formData.naturalMoon') }}
            </el-radio>
          </el-radio-group>
          <el-tooltip
            class="item"
            effect="light"
            :content="$t('formData.accordingToTheSelectedType')"
            placement="top"
          >
            <span>
              <el-icon><QuestionFilled /></el-icon>
            </span>
          </el-tooltip>
        </el-form-item>
        <el-form-item
          :label="$t('formData.timeFormat')"
          prop="timeFormat"
        >
          <el-radio-group v-model="dataForm.timeFormat">
            <el-radio :label="1">
              {{ $t('formData.customTime') }}
            </el-radio>
            <el-radio :label="2">
              {{ $t('formData.specifyTimeRange') }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="dataForm.timeFormat === 1">
          <el-form-item
            v-if="[1,3].includes(dataForm.timeType)"
            :label="$t('formData.customTime')"
            prop="time"
            class="custom-time"
          >
            <el-date-picker
              v-if="dataForm.timeType === 1"
              v-model="dataForm.time"
              type="daterange"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0),
                              new Date(2000, 2, 1, 23, 59, 59)]"
              unlink-panels
              range-separator="-"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
              :picker-options="pickerOptions"
              :clearable="false"
              @input="daterangeChange"
            />
            <el-date-picker
              v-else-if="dataForm.timeType === 3"
              v-model="dataForm.time"
              type="monthrange"
              unlink-panels
              range-separator="-"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
              :picker-options="pickerOptions"
              :clearable="false"
              @input="daterangeChange"
            />
          </el-form-item>
          <el-form-item
            v-if="dataForm.timeType===2"
            :label="$t('formData.customTime')"
            prop="tempDateWeek"
            class="custom-time"
          >
            <el-date-picker
              v-model="dataForm.tempDateWeek"
              :picker-options="{'firstDayOfWeek': 1}"
              type="week"
              format="YYYY [第] ww [周]"
              :clearable="false"
              :placeholder="$t('formData.selectWeek')"
              @change="Week"
            />
          </el-form-item>
        </template>
        <el-form-item
          v-if="dataForm.timeFormat === 2"
          :label="$t('formData.timeLimit')"
          prop="timeRamge"
          style="width:500px;"
        >
          <el-input
            v-model="dataForm.timeRamge"
            :placeholder="$t('formData.pleaseEnterTheTime')"
            @change="setTimeRamge"
          >
            <template #prepend>
              {{ $t('formData.near') }}
            </template>
            <template #append>
              {{ dataForm.timeType === 1? $t('formData.day') : dataForm.timeType === 2?$t('formData.week'):$t('formData.month') }}
              <el-tooltip
                class="item"
                effect="light"
                :content="$t('formData.timeTip')"
                placement="top"
              >
                <span>
                  <el-icon><QuestionFilled /></el-icon>
                </span>
              </el-tooltip>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          :label="$t('brand.serialNumber')"
          prop="seq"
        >
          <el-input-number
            v-model="dataForm.seq"
            controls-position="right"
            :min="1"
            :max="100000000"
            @change="seqChange"
          />
        </el-form-item>
        <el-form-item
          :label="$t('formData.selectIndicator')"
          prop="formItem"
          label-width="110px"
        >
          <el-card class="box-card">
            <el-row style="width:100%">
              <el-col
                v-for="item in formItemList"
                :key="item.id"
                :span="$t('language') === 'language' ? 8 : 4"
              >
                <el-link
                  v-if="!item.select"
                  :underline="false"
                  class="buttonClick"
                  @click="selectItem(item.id)"
                >
                  {{ item.value }}
                </el-link>
                <el-link
                  v-else
                  :underline="false"
                  type="success"
                  class="buttonClick"
                  @click="selectItem(item.id)"
                >
                  {{ item.value }}
                </el-link>
              </el-col>
            </el-row>
          </el-card>
        </el-form-item>
        <el-form-item>
          <el-tag
            v-for="item in formItemListSelect"
            :key="item.id"
            closable
            class="tag"
            type="info"
            @close="selectItem(item.id)"
          >
            {{ item.value }}
          </el-tag>&nbsp;&nbsp;
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div
            class="default-btn"
            @click="close()"
          >
            {{ $t('remindPop.cancel') }}
          </div>
          <div
            class="primary-btn default-btn"
            @click="onSubmit()"
          >
            {{ $t('remindPop.confirm') }}
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import moment from 'moment'

const emit = defineEmits(['refreshDataList'])

const dataForm = ref({
  formId: 0,
  formName: '',
  timeType: 1,
  timeFormat: 1,
  formItemIds: '',
  startTime: '',
  endTime: '',
  timeRamge: 1,
  time: '',
  seq: 1
})

const pickerOptions = {
  shortcuts: [{
    text: $t('formData.lastWeek'),
    onClick (picker) {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: $t('formData.lastMonth'),
    onClick (picker) {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: $t('formData.lastThreeMonths'),
    onClick (picker) {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      picker.$emit('pick', [start, end])
    }
  }]
}

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})

const validateNumber = (rule, value, callback) => {
  const reg = /[^\d]/
  if (reg.test(value)) {
    callback(new Error($t('formData.pleaseThan0')))
  } else {
    callback()
  }
}
const validateFormName = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('formData.theReportNameCannotBeEmpty')))
  } else {
    callback()
  }
}
const dataRule = reactive({
  formName: [
    { required: true, message: $t('formData.theReportNameCannotBeEmpty'), trigger: 'blur' },
    { validator: validateFormName, trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: $t('formData.startTimeCannotBeEmpty'), trigger: 'blur' }
  ],
  endTime: [
    { required: true, message: $t('formData.endTimeCannotBeEmpty'), trigger: 'blur' }
  ],
  timeRamge: [
    { required: true, message: $t('formData.endTimeCannotBeEmpty'), trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ],
  time: [
    { required: true, message: $t('formData.timeCannotBeEmpty'), trigger: 'blur' }
  ],
  tempDateWeek: [
    { required: true, message: $t('formData.timeCannotBeEmpty'), trigger: 'blur' }
  ]
})

// 获取分类数据 formType true:推荐报表
const visible = ref(false)
const formItemListSelect = ref([])
const init = (id, fromType) => {
  visible.value = true
  dataForm.value.formId = id || 0
  nextTick(() => {
    dataForm.value.formName = ''
    dataForm.value.content = ''
    dataForm.value.fromType = 1
    dataForm.value.timeType = 1
    dataForm.value.timeFormat = 1
    dataForm.value.formItemIds = ''
    dataForm.value.timeRamge = 1
    dataForm.value.seq = 1
    dataForm.value.time = ''
    dataForm.value.startTime = ''
    dataForm.value.endTime = ''
    delete dataForm.value.tempDateWeek
    formItemListSelect.value = []
    dataFormRef.value?.resetFields()
  })
  if (dataForm.value.formId) {
    // 获取产品数据
    http({
      url: http.adornUrl(`/platform/form/info/${dataForm.value.formId}`),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.value = data
      if (fromType) {
        dataForm.value.recommendForm = fromType
        dataForm.value.formId = 0
      }
      if (dataForm.value.timeType === 2) {
        dataForm.value.tempDateWeek = dataForm.value.startTime
      } else {
        dataForm.value.time = dataForm.value.startTime && dataForm.value.endTime ? [moment(dataForm.value.startTime, 'YYYY-MM-DD'), moment(dataForm.value.endTime, 'YYYY-MM-DD')] : []
      }
      getFormItem()
    })
  } else {
    nextTick(() => {
      dataFormRef.value?.resetFields()
      dataForm.value.recommendForm = fromType
      dataForm.value.imgUrl = ''
    })
    getFormItem()
  }
}
const Week = () => {
  const date = new Date(dataForm.value.tempDateWeek)
  dataForm.value.startTime = moment(date).add(-1, 'd').format('YYYY-MM-DD hh:mm:ss')
  dataForm.value.endTime = moment(date).add(5, 'd').format('YYYY-MM-DD hh:mm:ss')
}
const seqChange = () => {
  if (!dataForm.value.seq) {
    dataForm.value.seq = 1
  }
}
/**
 * 获取报表项数据
 */
const formItemList = ref([])
const getFormItem = () => {
  http({
    url: http.adornUrl('/platform/form/getFormItem'),
    method: 'get',
    params: http.adornParams({
      type: 1
    })
  }).then(({ data }) => {
    formItemList.value = data
    if (dataForm.value.formItemIds) {
      const ids = dataForm.value.formItemIds.split(',')
      formItemList.value.forEach(element => {
        if (ids.indexOf(element.id.toString()) > -1) {
          element.select = true
          formItemListSelect.value.push(element)
        }
      })
    }
  })
}
/**
 * 指定时间范围输入框验证
 */
const setTimeRamge = () => {
  const num = Math.round(dataForm.value.timeRamge)
  dataForm.value.timeRamge = num < 1 ? 1 : num
  if (num >= 100000000) {
    dataForm.value.timeRamge = 100000000
  }
}
/**
 * 选择开始时间/结束时间触发事件
 */
const daterangeChange = (e) => {
  if (e) {
    dataForm.value.time = [e[0], e[1]]
  } else {
    dataForm.value.time = []
  }
}
/**
 * 选择报表项
 */
const selectItem = (id) => {
  formItemListSelect.value = []
  formItemList.value.forEach(element => {
    if (element.id === id) {
      element.select = !element.select
    }
    if (element.select) {
      formItemListSelect.value.push(element)
    }
  })
}
// 表单提交
const dataFormRef = ref(null)
let isSubmit = true
const onSubmit = () => {
  dataForm.value.recommendForm = false
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (formItemListSelect.value.length < 1) {
        ElMessage.error($t('formData.pleaseSelectAnIndicator'))
        return
      }
      if (!isSubmit) {
        return true
      }
      if (dataForm.value.timeFormat === 1) {
        if (dataForm.value.timeType === 1 || dataForm.value.timeType === 3) {
          dataForm.value.startTime = moment(dataForm.value.time[0]).format('YYYY-MM-DD hh:mm:ss')
          dataForm.value.endTime = moment(dataForm.value.time[1]).format('YYYY-MM-DD hh:mm:ss')
        }
      }
      isSubmit = false
      dataForm.value.formItemIds = getFormItemIds()
      const param = JSON.parse(JSON.stringify(dataForm.value))
      delete param.tempDateWeek
      http({
        url: http.adornUrl('/platform/form'),
        method: param.formId ? 'put' : 'post',
        data: http.adornData(param)
      }).then(() => {
        ElMessage({
          message: $t('remindPop.succeeded'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            isSubmit = true
            visible.value = false
            emit('refreshDataList', page)
          }
        })
      }).catch(() => {
        isSubmit = true
      })
    }
  })
}
/**
 * 获取已选择的报表项id
 */
const getFormItemIds = () => {
  let ids = ''
  formItemListSelect.value.forEach(item => {
    ids = ids + item.id + ','
  })
  ids = ids.substring(0, ids.length - 1)
  return ids
}
// 关闭对话框回调
const closeDialogHandle = () => {
  dataFormRef.value?.resetFields()
}
/**
* 关闭弹窗
*/
const close = () => {
  visible.value = false
}

defineExpose({
  init
})

</script>
<style lang="scss" scoped>
.tag {
  margin: 0 10px 5px;
}
.components-add-or-update{
  .custom-time :deep(.el-form-item__content) {
    display: block;
  }
  .time-type{
    position: relative;
    :deep(.el-form-item__label){
      padding-right: 26px;
    }
    :deep(.el-tooltip__trigger){
      position: absolute;
      left: -25px;
      top: 2px;
    }
  }
}
</style>
